package com.riko.comic.core.exception;

import com.riko.comic.core.result.ResultCode;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Repository;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;

/**
 * 异常处理
 *
 * @author riko
 * @since 2021/10/29
 */
@Repository
public class CustomHandleException implements HandlerExceptionResolver {

    private static final Log log = LogFactory.getLog(CustomHandleException.class);

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) {
        // 定义异常信息
        String msg;

        // 判断异常类型
        if (exception instanceof BaseException) {
            // 如果是自定义异常，读取异常信息
            msg = exception.getMessage();
        } else {
            // 如果是非自定义异常，则取错误堆栈，从堆栈中获取异常信息
            Writer out = new StringWriter();
            PrintWriter s = new PrintWriter(out);
            exception.printStackTrace(s);
            msg = out.toString();

        }
        log.error(msg);

        ModelAndView modelAndView = new ModelAndView();

        // 把错误信息发给相关人员,邮件,短信等方式
        // 返回错误页面，给用户友好页面显示错误信息
        ResultCode resultCode = ResultCode.getByMessage(msg);
        if(resultCode!=null){
            modelAndView.addObject("msg", "页面出现异常("+resultCode.getCode()+":"+resultCode.getMessage()+")，请联系管理员QQ：123456");
        }else {
            modelAndView.addObject("msg", "页面出现未知异常，请联系管理员QQ：123456");
        }
        modelAndView.setViewName("error");

        return modelAndView;
    }
}